﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CallCenter.Model;

namespace CallCenter.DAL
{
    public class SeatsDAL
    {
        /// <summary>
        /// 将DataRow转换成实体类型
        /// </summary>
        /// <param name="row"></param>
        /// <returns></returns>
        private static SeatsModel ToSeatsModel(DataRow row)
        {
            SeatsModel model = new SeatsModel();
            model.Id = (Guid)row["Id"];
            model.UserName = (string)row["UserName"];
            model.Password = (string)row["Password"];
            model.IsDel = (bool)row["IsDel"];
            return model;
        }

        /// <summary>
        /// 根据用户名获得SeatsModel实体类型
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <returns></returns>
        public SeatsModel GetByUserName(string userName)
        {
            DataTable table = SqlHelper.ExecuteDataTable("select * from T_Seats where UserName=@userName and IsDel = 0",
                new SqlParameter("@userName", userName));
            if (table.Rows.Count <= 0)
            {
                return null;
            }
            else if (table.Rows.Count > 1)
            {
                throw new Exception();
            }
            else
            {
                SeatsModel model = ToSeatsModel(table.Rows[0]);
                return model;
            }
        }

        public SeatsModel GetById(Guid id)
        {
            DataTable table = SqlHelper.ExecuteDataTable("select * from T_Seats where Id = @id",
                new SqlParameter("@id", id));
            if (table.Rows.Count <= 0)
            {
                return null;
            }
            else if (table.Rows.Count > 1)
            {
                throw new Exception("出错了");
            }
            else
            {
                return ToSeatsModel(table.Rows[0]);
            }
        }

        public int UpdatePassword(SeatsModel seat)
        {
            return SqlHelper.ExecuteNonQuery("update T_Seats set Password = @password where UserName=@username",
                new SqlParameter("@password", seat.Password),
                new SqlParameter("@username", seat.UserName));
        }
    }
}
